package com.metaverse.backend.domain;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.metaverse.backend.annotations.ExcelTitle;
import com.metaverse.backend.annotations.Searchable;
import com.metaverse.backend.config.Views;
import com.metaverse.backend.enums.UserStatus;
import com.metaverse.backend.security.Authority;
import com.metaverse.backend.utils.UserAuthoritySerializer;
import io.netty.channel.Channel;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.BatchSize;

import javax.persistence.*;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(indexes={
        @Index(name = "openid", columnList = "openid", unique = true),
})
@ExcelTitle("用户")
@ApiModel("用户信息")
public class User extends BaseEntity implements Serializable {

    @ApiModelProperty("用户uid")
    private String uid;

    @Size(min = 1, max = 50)
    @ExcelProperty("用户唯一标识")
    @ApiModelProperty("用户唯一标识")
    private String openid;//用户唯一标识

    @Searchable
    @ExcelProperty("用户名")
    @ApiModelProperty("用户名称")
    private String username;

    @ExcelProperty("用户昵称")
    @ApiModelProperty("用户昵称")
    private String nickname;

    @ExcelProperty("头像")
    @ApiModelProperty("头像")
    private String avatar;

    @ExcelIgnore
    @JsonView(Views.RedisView.class)
    private String password;

    @ApiModelProperty("用户状态")
    @Enumerated(EnumType.STRING)
    @Column(nullable = false, columnDefinition = "varchar(255) default 'NORMAL' ")
    private UserStatus status = UserStatus.NORMAL;


    @ExcelProperty("是否是管理员")
    @ApiModelProperty("是否是管理员")
    private boolean admin;



    @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.DETACH})
    @JoinTable(
            name = "user_authority",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))},
            inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name", foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))})
    @BatchSize(size = 20)
    @ExcelIgnore
    @JsonSerialize(using = UserAuthoritySerializer.class, as = HashSet.class)
    private Set<Authority> authorities = new HashSet<>();



    @Transient
    private Channel channel;



}
